#!/usr/bin/php
<?php
/*
 *   This file is part of verbum.
 *
 *   poat is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   poat is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with poat.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * 	 Copyright (c) 2008 Sergio Gabriel Teves <gabriel.sgt at gmail.com>
 */

require("bashcommon.php");

$starttime=mtime();
$blog =& LoggerManager::getLogger('bash_commitjob');
$logid = startlog("jobcommit");

$blog->info("Started");
$_log->info("Started");

define('CURRENT_DIR',dirname(__FILE__));
@chdir(CURRENT_DIR);

DEFINE('PYSVN',CURRENT_DIR.'/svncontrol.py');

if (!file_exists(SVN_LOCATION)) {
	createDir(SVN_LOCATION);
}

$job = new job;
$job->type=JOB_TYPE_UPSVN;
$job->statusid=JOB_STATUS_NEW;
$list = $loader->loadListBy($job,$job->listBy()); 

$_log->info("Job found: ".count($list));
$blog->info("Job found: ".count($list));

// FIRST UPDATE TO AVOID OTHERS TO TAKE IT
foreach ($list as $j) {
	$j->statusid = JOB_STATUS_RUN;
	$j->started=util::now();
	$loader->update($j);
}

$usernotList = new maplist;
$teamnotList = new maplist;

foreach ($list as $j) {
	$blog->debug("Processing JOB ". $j->id);
	$upload = new upload;
	$upload->id=$j->runhash;
	$r = $loader->get($upload);
	$userdata=util::stringToArray(util::unhide($j->extra)," ");
	$errmsg = "";
	$usr = $userdata[0];
	$pwd = $userdata[1];
	$cmt = $j->filler;
	$uplist=array();
	$CURRENT_USER = new user;
	$CURRENT_USER->userid=$j->userid;
	$loader->get($CURRENT_USER);
	if (String::isEmpty($CURRENT_USER->teamid) || $CURRENT_USER->teamid=="0") {
		$CURRENT_USER->teamid = $j->teamid;
	}
	if ($r) {
		$blog->debug("Processing UPLOAD ". $upload->id);	
		$upload->statusid=UPLOAD_RUN;
		$loader->update($upload);

		$prj = new project;
		$prj->id = $upload->projectid;
		$loader->get($prj);

		$team = new team;
		$team->id = $upload->teamid;
		$loader->get($team);
		
		$upd = new upload_data;
		$upd->objid=$upload->id;
		$udlist = $loader->loadListBy($upd,$upd->listOK());
		$prup = array();
		foreach ($udlist as $ud) {
			$pd = $ud->pjid;
			if (!isset($prup[$pd])) {
				$sprj = new project;
				$sprj->id = $pd;
				$loader->get($sprj);
				$prup[$pd] = $prj->path . str_replace('$LANG',$team->lang,$sprj->path);
				if (!file_exists(SVN_LOCATION.$prup[$pd])) {
					// CHECKOUT
					unset($ar);
					unset($retval);
					$blog->debug("Checking out ".$prup[$pd]);
					@exec(PYSVN." ".SVN_ROOT.$prup[$pd]." ".SVN_LOCATION.$prup[$pd],$ar,$retval);
					if ($retval!=0) {
						switch ( $retval ) {
							case 4:
								if ($errmsg!="") $errmsg.="\n";
								$errmsg=s("Failed retrieving ssl certificate.");
								break;
							case 3:
								if ($errmsg!="") $errmsg.="\n";
								$errmsg=s("Login failed. Verify credentials.");
								break;
							case 2:
								if ($errmsg!="") $errmsg.="\n";
								$errmsg=s("Unknown error.");
								break;
							default:
								break;
						}
						if (count($ar)>0) {
							$blog->debug($ar);
							foreach ($ar as $erm) {
								if ($errmsg!="") $errmsg.="\n";
								$errmsg.=$erm;
							}
							$_log->error($errmsg);
							$blog->error($errmsg);
							break; 
						}
					}
				}
			}
		}
		if ($errmsg=="") {
			$tarname = UPLOAD_PATH."/".$upload->id.".tgz";
			$blog->debug("Extracting $tarname");
			$tar = new Archive_Tar($tarname);
			$tar->extract(SVN_LOCATION.$prj->path);
			unset($tar);
			$revp = array();
			foreach ($prup as $pi => $uppj) {
				$svnurl = SVN_ROOT.$uppj;
				$svnlocation = SVN_LOCATION.$uppj;
				$blog->debug("Processing $svnlocation");
				unset($ar);
				unset($retval);
				if ($upload->comment!="") {
					$cmm = String::format(s("{0}: {1}"), array($upload->userid,$upload->comment));
				} else {
					$cmm = $cmt;
				}
				$rev = exec(PYSVN." ".$svnurl." ".$svnlocation." ".$usr." ".$pwd." \"".$cmm."\"",$ar,$retval);
				if ($retval!=0) {
					if (count($ar)>0) {
						$blog->debug($ar);
						foreach ($ar as $erm) {
							if (strstr($erm,"Traceback")!==false) {
								break;
							}
							if ($errmsg!="") $errmsg.="\n";
							$errmsg.=$erm;
						}
						$errmsg = str_replace(SVN_LOCATION,"",$errmsg);
						$_log->error($errmsg);
						$blog->error($errmsg);
						break; 
					}
				} else {
					$revp[$pi]=$rev;
					$blog->info("Comitted ".$rev);
					$_log->info("Comitted ".$rev);
					$blog->debug($revp);
				}
			} 			
		}
		if ($errmsg!="") {
			sendMailFailUpload($CURRENT_USER,$errmsg);
			$upload->statusid=UPLOAD_FAIL;
			$loader->update($upload);
		} else {
			$blog->debug("Mark files");
			foreach ($udlist as $ud) {
				$file = new files($upload->projectid);
				$file->id=$ud->fileid;
				if ($loader->get($file)) {
					switch ($ud->filestatus) {
						case FILE_STATUS_TRANS:
							$file->statusid = FILE_STATUS_CHKPND;
							break;
						case FILE_STATUS_PROOF:
							$file->statusid = FILE_STATUS_DONE;
							break;
						default:
							$file->statusid = FILE_STATUS_CHKPND;
							break;
					}
					if (isset($revp[$file->prjid])) {
						$file->comment=String::format(s("Commited revision {0}.",$CURRENT_USER->lang),$revp[$file->prjid]);	
					} else {
						if (trim($cmt)!="") {
							$file->comment=$cmt;
						} // IF THE COORD DOESN'T ENTER A COMMENT, I LEAVE THE LAST ONE ENTERED.
					}
					$loader->update($file);
					$loader->execute(history::create($file,null,HIS_ACT_CMM));
					$usernotList->add($upload->userid,$file);
					$teamnotList->add($team->id,$file);
				}				
			}
			$loader->delete($upload);
			$loader->delete($upd);
			@unlink($tarname);
			//mailUploadDone($CURRENT_USER,$uplist,"ok",$upload->userid);
		}
	}
	$loader->delete($j);
}

$list = $usernotList->getAll();
foreach ($list as $k => $flist) {
	$u = new user;
	$u->userid=$k;
	if ($loader->get($u)) {
		mailJobUploadDone($u,$flist);	
	}
}
$list = $teamnotList->getAll();
foreach ($list as $k => $flist) {
	$u = new user;
	$u->teamid = $k;
	$u->groupid = array(GROUP_COORD,GROUP_SVN);
	$ulist = $loader->loadListBy($u, $u->listByFilters(null, "1006"));
	foreach ($ulist as $u) {
		mailJobUploadDone($u,$flist);
	}
}

$endtime=mtime();
endlog($logid);
$db->close();
$blog->info("Finished");
$_log->info("Finished");
$blog->info("============= * =============");
$_log->info("============= * =============");
$blog->info("Process time: ".sec2hms($endtime-$starttime,true));
$_log->info("Process time: ".sec2hms($endtime-$starttime,true));

?>